// 命名管道 mkfifo：单向, 可用于任意进程间通信
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define PIPE_PATH "/tmp/fajgfsd_863.pip"
int main() {
  if (access(PIPE_PATH, F_OK) == 0) {
    unlink(PIPE_PATH);
  }
  // 创建文件
  mkfifo(PIPE_PATH, 0666);

  int pid = fork();
  if (pid == 0) {
    char buf[1024] = {0};
    // 子进程 以读方式打开管道
    FILE *fp = fopen(PIPE_PATH, "rb");
    while (1) {
      int readLen = fread(buf, sizeof(char), 1024, fp);
      if (readLen > 0) {
        printf("[%d] recv data is: %s", getpid(), buf);
        memset((void *)buf, 0, 1024);
      } else {
        break;
      }
    }

  } else {
    // 父进程 以写方式打开
    FILE *fp = fopen(PIPE_PATH, "wb");
    for (int i = 0; i < 10; i++) {
      fwrite("hello\n", sizeof(char), 1024, fp);
      sleep(1);
    }
  }
  return 0;
}
